/* 
 * Copyright (C) 2011, WordCards4Me Project - http://code.google.com/p/wordcards4me/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.wordcards4me;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;

public class FileBrowser extends List implements CommandListener {

	private static final String FILE_SEPARATOR =
		/*System.getProperty("file.separator")!= null ? System.getProperty("file.separator") :*/ "/";
		
	private static final String UPPER_DIRECTORY = "..";
	
	private static final String FILE_FORMAT_EXTENSION = "*.wc";

	// Images
	private static final Image FILE_IMAGE = CardMidlet.loadImage("/file.png");
	private static final Image FOLEDER_IMAGE = CardMidlet.loadImage("/folder.png");
	
	// Commands
	private Command open = new Command("Open", Command.ITEM, 1);
	private Command exit = new Command("Exit", Command.EXIT, 1);
	
	private Vector rootList = new Vector();
	private FileConnection connection;
	
	public FileBrowser() {
		super("File Browser", List.IMPLICIT);
		
		setCommandListener(this);
		addCommand(open);
		addCommand(exit);
		setSelectCommand(open);
		
		loadRoots();
		showRoots();
	}
	
	public void commandAction(Command command, Displayable displayable) {
		if(command == open) {
			processOpenCommand();
		} else if(command == exit) {
			CardMidlet.goBackward();
		}
	}

	private void loadRoots() {
		try {
			rootList.removeAllElements();
			Enumeration e = FileSystemRegistry.listRoots();
			while (e.hasMoreElements()) {
				rootList.addElement(FILE_SEPARATOR + (String) e.nextElement());
			}
		} catch (Throwable e) {
			//TODO: show error screen
		}
	}
	
	private void showRoots() {
		setTitle("File Browser");
		deleteAll();
		Enumeration e = rootList.elements();
		while (e.hasMoreElements()) {
			String root = (String) e.nextElement();
			append(root.substring(1), FOLEDER_IMAGE);
		}
	}
	
	private void openSelected() throws IOException, SecurityException {
		int selectedIndex = getSelectedIndex();
		if (selectedIndex >= 0) {
			String selectedFileName = getString(selectedIndex);
			if (selectedFileName.endsWith(FILE_SEPARATOR)) {
				if (connection == null) {
					connection = (FileConnection) 
								   Connector.open("file:///" + selectedFileName, Connector.READ);
				} else {
					connection.setFileConnection(selectedFileName);
				}
				showCurrentFile();
			} else if (selectedFileName.equals(UPPER_DIRECTORY)) {
				if (rootList.contains(connection.getPath() + connection.getName())) {
					showRoots();
				} else {
					connection.setFileConnection(UPPER_DIRECTORY);
					showCurrentFile();
				}
			} else {
				CardMidlet.loadAndShowCardStack(connection.getURL() + selectedFileName);
			}
		}
	}
	
	private void processOpenCommand() {
		new Thread(new Runnable() {
			public void run() {
				try {
					openSelected();
				} catch (Exception e) {
					// TODO: show error screen
				}
			}
		}).start();
	}
	  
	private void showCurrentFile() throws IOException, SecurityException {
		setTitle(connection.getURL());
		deleteAll();
		append(UPPER_DIRECTORY, FOLEDER_IMAGE);
		Enumeration files = connection.list("*", false);
		// show folders
		while (files.hasMoreElements()) {
			String fileName = (String) files.nextElement();
			append(fileName, fileName.endsWith(FILE_SEPARATOR) ? FOLEDER_IMAGE : FILE_IMAGE);
		}
		// show files with cards
		Enumeration cards = connection.list(FILE_FORMAT_EXTENSION, false);
		while (cards.hasMoreElements()) {
			append((String) cards.nextElement(), FILE_IMAGE);
		}
	}
}
